package com.wc.算法提高课.A第一章_动态规划.数位DP.度的数量;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

/**
 * @Author congge
 * @Date 2025/5/24 14:46
 * @description
 * https://www.acwing.com/problem/content/1083/
 */
public class Main {
    /**
     * 灵神的模板：无敌
     */
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int N = 40, M = 25;
    static int[][] f = new int[N][M];
    static int[] nums = new int[N];
    static int L, R, K, base, len = 0;

    public static void main(String[] args) {
        L = sc.nextInt();
        R = sc.nextInt();
        K = sc.nextInt();
        base = sc.nextInt();
        out.println(dp(R) - dp(L - 1));
        out.flush();
    }

    static int dp(int x) {
        for (int i = 0; i < N; i++) Arrays.fill(f[i], -1);
        len = 1;
        // 将 x 转换到 b 进制
        while (x > 0) {
            nums[len++] = x % base;
            x /= base;
        }
        return dfs(len - 1, 0, true, false);
    }

    static int dfs(int i, int k, boolean limit, boolean num) {
        if (k > K) return 0;
        if (!limit && num && f[i][k] != -1) return f[i][k];

        if (i == 0) {
            return k == K ? 1 : 0;
        }

        int up = limit ? nums[i] : base - 1;
        int res = 0;
        for (int d = 0; d <= Math.min(up, 1) ; d++) {
            res += dfs(i - 1, k + d, limit && d == up, num || d > 0);
        }

        if (!limit && num) f[i][k] = res;

        return res;
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}

